import React, { Component } from "react";
// import axios from "axios";
import PubSub from "pubsub-js";

export default class Search extends Component {
  search = async () => {
    //获取用户的输入(连续解构赋值+重命名)
    const {
      keyWordElement: { value: keyWord },
    } = this;
    //发送请求前通知List更新状态
    PubSub.publish("getData", { isFirst: false, isLoading: true });
    //发送网络请求,使用fetch
    // fetch(`/api1/search/users?q=${keyWord}`)
    //   .then((response) => {
    //     console.log("联系服务器成功");
    //     return response.json();
    //   })
    //   .then((res) => {
    //     console.log("获取数据成功");
    //     //请求成功后通知List更新状态
    //     PubSub.publish("getData", {
    //       isLoading: false,
    //       users: res.items,
    //     });
    //   })
    //   .catch((error) => {
    //     console.log("请求出错", error);
    //   });

    // 优化后的fetch
    try {
      const response = await fetch(`/api1/search/users?q=${keyWord}`);
      const data = response.json();
      //请求成功后通知List更新状态
      PubSub.publish("getData", {
        isLoading: false,
        users: data.items,
      });
    } catch (error) {
      console.log("请求出错", error);
      //请求失败后通知List更新状态
      PubSub.publish("getData", { isLoading: false, err: error.message });
    }
  };

  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">搜索github用户</h3>
        <div>
          <input
            ref={(c) => (this.keyWordElement = c)}
            type="text"
            placeholder="输入关键词点击搜索"
          />
          &nbsp;
          <button onClick={this.search}>搜索</button>
        </div>
      </section>
    );
  }
}
